package top.z.template.parse.ast.expression;

import top.z.template.Context;
import top.z.template.Error;
import top.z.template.Template;
import top.z.template.parse.Ast.Expression;
import top.z.template.parse.Span;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Character, 用单引号括起来, 支持转义: \n, \r, \t, \' 和 \\
 */
public class CharacterLiteral extends Expression {

    private final Character value;

    public CharacterLiteral(Span span) {
        super(span);
        String text = span.getText();
        if (text.length() > 3) {
            if (text.charAt(2) == 'n') {        // \\n
                this.value = '\n';
            } else if (text.charAt(2) == 'r') { // \\r
                this.value = '\r';
            } else if (text.charAt(2) == 't') { // \\t
                this.value = '\t';
            } else if (text.charAt(2) == '\\') { // \\\
                this.value = '\\';
            } else if (text.charAt(2) == '\'') { // \\'
                this.value = '\'';
            } else {
                throw Error.error("Unknown escape sequence '" + span.getText() + "'.", span);
            }
        } else {
            this.value = span.getText().charAt(1);
        }
    }

    public Character getValue() {
        return value;
    }

    @Override
    public Object evaluate(Template template, Context context, OutputStream out) throws IOException {
        return value;
    }
}
